/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Configurations;

import java.sql.*;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author mizheng
 */
@WebServlet(name = "FileUpload", urlPatterns = {"/FileUpload"})
public class FileUploadServlet extends HttpServlet {

    private ServletConfig config;
    //Setting JSP page
    String page = "upload.jsp";

    public void init(ServletConfig config)
            throws ServletException {

        this.config = config;

    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    public void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        //to get the content type information from JSP Request Header
        String contentType = request.getContentType();
        //here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
        if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
            DataInputStream in = new DataInputStream(request.getInputStream());
            //we are taking the length of Content type data
            int formDataLength = request.getContentLength();
            byte dataBytes[] = new byte[formDataLength];
            int byteRead = 0;
            int totalBytesRead = 0;
            //this loop converting the uploaded file into byte code
            while (totalBytesRead < formDataLength) {
                byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                totalBytesRead += byteRead;
            }

            String file = new String(dataBytes);
            //for saving the file name
            String saveFile = file.substring(file.indexOf("filename=\"") + 10);
            saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
            saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
            int lastIndex = contentType.lastIndexOf("=");
            String boundary = contentType.substring(lastIndex + 1, contentType.length());
            int pos;
            //extracting the index of file 
            pos = file.indexOf("filename=\"");
            pos = file.indexOf("\n", pos) + 1;
            pos = file.indexOf("\n", pos) + 1;
            pos = file.indexOf("\n", pos) + 1;
            int boundaryLocation = file.indexOf(boundary, pos) - 4;
            int startPos = ((file.substring(0, pos)).getBytes()).length;
            int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;


            // creating a new file with the same name and writing the content in new file
            File currentDirectory = new File(".").getCanonicalFile();
            File dest = new File(currentDirectory + "/docroot/" + saveFile);
            System.out.println("Is chosen file a directory?: " + dest.isDirectory());
            if (!dest.isDirectory()) { // When a user doesn't choose a file the dest is a directory
                if (saveFile.indexOf(".zip") != -1 || (saveFile.indexOf(".txt") != -1)) {
                    FileOutputStream fileOut = new FileOutputStream(dest);
                    fileOut.write(dataBytes, startPos, (endPos - startPos));
                    fileOut.flush();
                    fileOut.close();
                    System.out.println(dest.getAbsolutePath());

                    request.setAttribute("uploaded", "zip");
                    // Zip file uploaded
                    if (saveFile.indexOf(".zip") != -1) {
                        System.out.println("Zip file uploaded");
                        FileOperations.unzip(dest);
                    }

                    // Data file uploaded
                    if (saveFile.indexOf(".txt") != -1) {
                        System.out.println("Check if it is AY or OTS file");
                        OTSFile ots = new OTSFile(dest);
                        AYFile ay = new AYFile(dest);
                        if (ots.getSuccess()) { // Matches OTS format add to database
                            System.out.println("Successfully mapped file to OTS");
                            Connection con = null;
                            ResultSet rs = null;
                            PreparedStatement ps = null;
                            try {
                                Class.forName(MySQL.DB_DRIVER);
                                con = DriverManager.getConnection(MySQL.DB_URL, MySQL.DB_USER, MySQL.DB_PASS);
                                String numQs = "";
                                for (int i = 0; i < ots.getOrder().size(); i++) {
                                    numQs = numQs + "?";
                                    if (i != ots.getOrder().size() - 1) {
                                        numQs = numQs + ", ";
                                    }
                                }
                                String sql = "INSERT INTO " + MySQL.DB_SCORES + " (" + ots.toStringOrder() + ") " + "VALUES (" + numQs + ")";
                                ps = con.prepareStatement(sql);
                                for (int j = 0; j < ots.getData().size(); j++) {
                                    for (int i = 1; i <= ots.getOrder().size(); i++) {
                                        ps.setString(i, ots.getData().get(j).get(i - 1));
                                    }
                                    ps.execute(); // Missing Upload Date and Phd or MBS program
                                    System.out.println(ps.toString());
                                    System.out.println("A row was added to Official Score Database");
                                }
                            } catch (Exception e) {

                                System.out.println("Exception is ;" + e);

                            }
                            request.setAttribute("uploaded", "ots");
                        } else if (ay.getSuccess()) {
                            System.out.println("Successfully mapped file to AY");
                            Connection con = null;
                            ResultSet rs = null;
                            PreparedStatement ps = null;
                            try {
                                Class.forName(MySQL.DB_DRIVER);
                                con = DriverManager.getConnection(MySQL.DB_URL, MySQL.DB_USER, MySQL.DB_PASS);
                                String numQs = "";
                                for (int i = 0; i < ay.getOrder().size(); i++) {
                                    numQs = numQs + "?";
                                    if (i != ay.getOrder().size() - 1) {
                                        numQs = numQs + ", ";
                                    }
                                }
                                String sql = "INSERT INTO " + MySQL.DB_APPS + " (" + ay.toStringOrder() + ") " + "VALUES (" + numQs + ")";
                                ps = con.prepareStatement(sql);
                                for (int j = 0; j < ay.getData().size(); j++) {
                                    for (int i = 1; i <= ay.getOrder().size(); i++) {
                                        ps.setString(i, ay.getData().get(j).get(i - 1));
                                    }
                                    ps.execute(); // Missing Upload Date and Phd or MBS program
                                    System.out.println(ps.toString());
                                    System.out.println("A row was added to Application Database");
                                }
                            } catch (Exception e) {

                                System.out.println("Exception is ;" + e);

                            }
                            request.setAttribute("uploaded", "ay");
                        }
                    }

                    //dest.delete(); // Delete file afterwards
                    //dest.deleteOnExit();

                    System.out.println("File Uploaded Successfully.");
                    System.out.println("Redirect to index.jsp");
                } else {
                    request.setAttribute("uploaded", "badFile");
                    System.out.println("invalid file type");
                }
            }
            in.close();
        }

        //Disptching request

        RequestDispatcher dispatcher = request.getRequestDispatcher(page);

        if (dispatcher != null) {

            dispatcher.forward(request, response);

        }
    }
    
     public void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
         response.sendRedirect(page);
     }
     
}
